/**
 * 缓存搜索项
 * @param storageKey 缓存key值
 * @param dataTableRef 列表ref
 * @param searchInfo 搜索内容
 * @returns
 */
export function useRestoreSearch(moduleKey: string) {
  const storageKey = `search-storage-${moduleKey}`
  const pageNumKey = `${storageKey}-pageNum`
  const pageSizeKey = `${storageKey}-pageSize`

  /**
   * 初始化hook
   */
  const initRestoreSearch = () => {
    const sessionKeys = Object.keys(sessionStorage).filter((key) => key.includes('search-storage-'))
    sessionKeys.forEach((key) => {
      let little = null
      if (key.includes('-pageNum')) {
        little = key.replace('search-storage-', '').replace('-pageNum', '')
      } else if (key.includes('-pageSize')) {
        little = key.replace('search-storage-', '').replace('-pageSize', '')
      } else {
        little = key.replace('search-storage-', '')
      }
      if (!moduleKey.includes(little)) {
        sessionStorage.removeItem(key)
      }
    })
  }
  initRestoreSearch()

  /**
   * 往sessionStorage中缓存查询内容
   * @param searchInfo 查询内容对象
   */
  const setSearchStorage = (searchInfo: any) => {
    const conditions = {
      ...searchInfo
    }
    sessionStorage.setItem(storageKey, JSON.stringify(conditions))
  }

  /**
   * 往sessionStorage中缓存页数信息
   * @param pageNum 页码
   */
  const setPageNumStorage = (pageNum: any) => {
    sessionStorage.setItem(pageNumKey, pageNum)
  }

  /**
   * 往sessionStorage中缓存每页多少条的信息
   * @param pageSize 每页多少条
   */
  const setPageSizeStorage = (pageSize: any) => {
    sessionStorage.setItem(pageSizeKey, pageSize)
  }

  /**
   * 将sessionStorage中的缓存内容取出
   * @returns
   */
  const restoreSearchStorage = () => {
    const resStr = sessionStorage.getItem(storageKey)
    removeSearchStorage()
    if (resStr && resStr !== '{}') {
      const conditions = JSON.parse(resStr)
      return conditions
    }
    return {}
  }

  /**
   * 将sessionStorage中的缓存页数取出
   * @returns
   */
  const restorePageNumStorage = () => {
    const resStr = sessionStorage.getItem(pageNumKey)
    removePageNumStorage()
    if (resStr) {
      return +resStr
    }
    return 1
  }

  /**
   * 将sessionStorage中的缓存每页多少条取出
   * @returns
   */
  const restorePageSizeStorage = () => {
    const resStr = sessionStorage.getItem(pageSizeKey)
    removePageSizeStorage()
    if (resStr) {
      return +resStr
    }
    return 10
  }

  /**
   * 将sessionStorage中的缓存移除
   */
  const removeSearchStorage = () => {
    sessionStorage.removeItem(storageKey)
  }

  /**
   * 将sessionStorage中缓存的页数移除
   */
  const removePageNumStorage = () => {
    sessionStorage.removeItem(pageNumKey)
  }

  /**
   * 将sessionStorage中缓存的每页多少条移除
   */
  const removePageSizeStorage = () => {
    sessionStorage.removeItem(pageSizeKey)
  }

  return {
    setSearchStorage,
    setPageNumStorage,
    setPageSizeStorage,
    restoreSearchStorage,
    restorePageNumStorage,
    restorePageSizeStorage
  }
}
